import React, { useState, useEffect } from 'react'
import { Card, List, Button, Tag, message, Row, Col, Modal, Form, Input, Select, Statistic } from 'antd'
import { useNavigate } from 'react-router-dom'
import { FileTextOutlined, CheckCircleOutlined, ClockCircleOutlined, ArrowLeftOutlined, UserOutlined } from '@ant-design/icons'

interface GovernanceItem {
  id: string
  title: string
  type: 'complaint' | 'suggestion' | 'application' | 'report'
  submitter: string
  submitDate: string
  status: 'pending' | 'processing' | 'completed' | 'rejected'
  village: string
  description: string
  response?: string
  responseDate?: string
  priority: 'low' | 'medium' | 'high'
}

const DigitalGovernance: React.FC = () => {
  const navigate = useNavigate()
  const [items, setItems] = useState<GovernanceItem[]>([])
  const [loading, setLoading] = useState(true)
  const [isSubmitModalVisible, setIsSubmitModalVisible] = useState(false)

  // mock数据 - 与后台管理模块关联
  useEffect(() => {
    const mockItems: GovernanceItem[] = [
      {
        id: '1',
        title: '道路维修申请',
        type: 'application',
        submitter: '张大山',
        submitDate: '2024-01-10',
        status: 'completed',
        village: '幸福村',
        description: '村内主干道路面破损严重，申请维修',
        response: '已安排维修队伍，预计本周内完成修复',
        responseDate: '2024-01-12',
        priority: 'high'
      },
      {
        id: '2',
        title: '环境卫生建议',
        type: 'suggestion',
        submitter: '李小花',
        submitDate: '2024-01-08',
        status: 'processing',
        village: '和平村',
        description: '建议增加垃圾分类收集点，改善环境卫生',
        priority: 'medium'
      },
      {
        id: '3',
        title: '路灯故障投诉',
        type: 'complaint',
        submitter: '王老五',
        submitDate: '2024-01-05',
        status: 'pending',
        village: '富裕村',
        description: '村口路灯连续多日不亮，影响夜间出行安全',
        priority: 'high'
      },
      {
        id: '4',
        title: '文化活动场地申请',
        type: 'application',
        submitter: '赵六',
        submitDate: '2024-01-12',
        status: 'processing',
        village: '幸福村',
        description: '申请使用村文化广场举办春节联欢晚会',
        priority: 'medium'
      },
      {
        id: '5',
        title: '供水系统故障报告',
        type: 'report',
        submitter: '钱七',
        submitDate: '2024-01-15',
        status: 'completed',
        village: '和平村',
        description: '村内供水系统出现故障，影响村民正常用水',
        response: '已修复供水系统，恢复正常供水',
        responseDate: '2024-01-16',
        priority: 'high'
      },
      {
        id: '6',
        title: '乡村绿化美化建议',
        type: 'suggestion',
        submitter: '孙八',
        submitDate: '2024-01-18',
        status: 'processing',
        village: '富裕村',
        description: '建议在村内主要道路两侧种植观赏树木，美化环境',
        priority: 'low'
      },
      {
        id: '7',
        title: '噪音扰民投诉',
        type: 'complaint',
        submitter: '周九',
        submitDate: '2024-01-20',
        status: 'pending',
        village: '幸福村',
        description: '村内施工工地夜间施工噪音过大，影响休息',
        priority: 'medium'
      },
      {
        id: '8',
        title: '公共设施维护申请',
        type: 'application',
        submitter: '吴十',
        submitDate: '2024-01-22',
        status: 'completed',
        village: '和平村',
        description: '申请对村内公共健身器材进行维护保养',
        response: '已完成健身器材维护，可以正常使用',
        responseDate: '2024-01-25',
        priority: 'medium'
      },
      {
        id: '9',
        title: '交通安全隐患报告',
        type: 'report',
        submitter: '郑十一',
        submitDate: '2024-01-25',
        status: 'processing',
        village: '富裕村',
        description: '村口十字路口缺乏交通标志，存在安全隐患',
        priority: 'high'
      },
      {
        id: '10',
        title: '文化活动经费申请',
        type: 'application',
        submitter: '王十二',
        submitDate: '2024-01-28',
        status: 'pending',
        village: '幸福村',
        description: '申请文化活动经费用于举办村民文艺汇演',
        priority: 'medium'
      }
    ]

    setTimeout(() => {
      setItems(mockItems)
      setLoading(false)
    }, 1000)
  }, [])

  const handleSubmit = (values: any) => {
    const newItem: GovernanceItem = {
      id: Date.now().toString(),
      title: values.title,
      type: values.type,
      submitter: '当前用户',
      submitDate: new Date().toISOString().split('T')[0],
      status: 'pending',
      village: values.village,
      description: values.description,
      priority: values.priority
    }
    
    setItems([newItem, ...items])
    setIsSubmitModalVisible(false)
    message.success('提交成功，我们将尽快处理')
  }

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'complaint': return 'red'
      case 'suggestion': return 'blue'
      case 'application': return 'green'
      case 'report': return 'orange'
      default: return 'default'
    }
  }

  const getTypeText = (type: string) => {
    switch (type) {
      case 'complaint': return '投诉'
      case 'suggestion': return '建议'
      case 'application': return '申请'
      case 'report': return '报告'
      default: return type
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'orange'
      case 'processing': return 'blue'
      case 'completed': return 'green'
      case 'rejected': return 'red'
      default: return 'default'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending': return '待处理'
      case 'processing': return '处理中'
      case 'completed': return '已完成'
      case 'rejected': return '已拒绝'
      default: return status
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'low': return 'green'
      case 'medium': return 'orange'
      case 'high': return 'red'
      default: return 'default'
    }
  }

  const statistics = {
    total: items.length,
    pending: items.filter(item => item.status === 'pending').length,
    processing: items.filter(item => item.status === 'processing').length,
    completed: items.filter(item => item.status === 'completed').length
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/user-dashboard')}
              style={{ padding: '4px 8px' }}
            >
              返回
            </Button>
            <span>数字治理平台</span>
          </div>
        }
        style={{ marginBottom: '24px' }}
        extra={
          <Button type="primary" onClick={() => setIsSubmitModalVisible(true)}>
            提交事项
          </Button>
        }
      >
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={6}>
            <Statistic title="总事项" value={statistics.total} />
          </Col>
          <Col span={6}>
            <Statistic title="待处理" value={statistics.pending} valueStyle={{ color: '#faad14' }} />
          </Col>
          <Col span={6}>
            <Statistic title="处理中" value={statistics.processing} valueStyle={{ color: '#1890ff' }} />
          </Col>
          <Col span={6}>
            <Statistic title="已完成" value={statistics.completed} valueStyle={{ color: '#52c41a' }} />
          </Col>
        </Row>

        <List
          loading={loading}
          dataSource={items}
          renderItem={item => (
            <List.Item
              actions={[
                <Button type="link">查看详情</Button>
              ]}
            >
              <List.Item.Meta
                avatar={<FileTextOutlined style={{ fontSize: '24px', color: '#1890ff' }} />}
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <span>{item.title}</span>
                    <Tag color={getTypeColor(item.type)}>{getTypeText(item.type)}</Tag>
                    <Tag color={getStatusColor(item.status)}>{getStatusText(item.status)}</Tag>
                    <Tag color={getPriorityColor(item.priority)}>优先级：{item.priority}</Tag>
                    <Tag color="blue">{item.village}</Tag>
                  </div>
                }
                description={
                  <div>
                    <p>{item.description}</p>
                    <Row gutter={16} style={{ marginTop: '8px' }}>
                      <Col span={6}>
                        <UserOutlined /> 提交人：{item.submitter}
                      </Col>
                      <Col span={6}>
                        <ClockCircleOutlined /> 提交时间：{item.submitDate}
                      </Col>
                      {item.response && (
                        <Col span={12}>
                          <CheckCircleOutlined /> 回复：{item.response}（{item.responseDate}）
                        </Col>
                      )}
                    </Row>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 提交事项弹窗 */}
      <Modal
        title="提交治理事项"
        open={isSubmitModalVisible}
        onCancel={() => setIsSubmitModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="事项类型"
            name="type"
            rules={[{ required: true, message: '请选择事项类型' }]}
          >
            <Select placeholder="请选择事项类型">
              <Select.Option value="complaint">投诉</Select.Option>
              <Select.Option value="suggestion">建议</Select.Option>
              <Select.Option value="application">申请</Select.Option>
              <Select.Option value="report">报告</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入事项标题" />
          </Form.Item>

          <Form.Item
            label="所在村庄"
            name="village"
            rules={[{ required: true, message: '请选择所在村庄' }]}
          >
            <Select placeholder="请选择所在村庄">
              <Select.Option value="幸福村">幸福村</Select.Option>
              <Select.Option value="和平村">和平村</Select.Option>
              <Select.Option value="富裕村">富裕村</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="优先级"
            name="priority"
            rules={[{ required: true, message: '请选择优先级' }]}
          >
            <Select placeholder="请选择优先级">
              <Select.Option value="low">低</Select.Option>
              <Select.Option value="medium">中</Select.Option>
              <Select.Option value="high">高</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="详细描述"
            name="description"
            rules={[{ required: true, message: '请输入详细描述' }]}
          >
            <Input.TextArea rows={4} placeholder="请详细描述您的事项内容" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: '8px' }}>
              提交
            </Button>
            <Button onClick={() => setIsSubmitModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default DigitalGovernance